﻿using M_Quality.API.Application.Command.QualitygroupCommand;
using M_Quality.Domain.Dto;
using M_Quality.Domain;
using MediatR;
using M_Quality.API.Application.Command.QualityinspectionCommand;
using M_Quality.Repository.Interface;
using M_Quality.Repository.Impl;

namespace M_Quality.API.Application.CommandHandler.QualityinspectionHandler
{
    public class QualityinspectionshowCommandHandler : IRequestHandler<QualityinspectionshowCommand, PageDto<Qualityinspection>>
    {

        protected readonly IQualityinspectionRepository qualityinspectionRepository;

        public QualityinspectionshowCommandHandler(IQualityinspectionRepository qualityinspectionRepository)
        {
            this.qualityinspectionRepository = qualityinspectionRepository;
        }

        public async Task<PageDto<Qualityinspection>> Handle(QualityinspectionshowCommand request, CancellationToken cancellationToken)
        {
            var res = await qualityinspectionRepository.GetAsync(o => o.IsDeleted == false);

            if (!string.IsNullOrEmpty(request.QualityinspectionBH))
            {
                res = res.Where(o => o.QualityinspectionBH.Contains(request.QualityinspectionBH)).ToList();
            }
            if (request.CreatedDate!=null)
            {
                res = res.Where(o => o.CreatedDate==request.CreatedDate).ToList();
            }
            if (request.Pagesize == null)
            {
                request.Pagesize = res.Count();
            }
            if (request.Pageindex == null)
            {
                request.Pageindex = 1;
            }
            PageDto<Qualityinspection> page = new PageDto<Qualityinspection>();
            var size = request.Pagesize;
            var index = request.Pageindex;
            page.TotalCount = res.Count();
            page.PageCount = (int)Math.Ceiling(page.TotalCount * 1.0 / (int)size);
            page.list = res.OrderByDescending(o => o.QualityinspectionId).Skip(((int)index - 1) * (int)size).Take((int)size).ToList();
            return page;
        }
    }
}
